package com.lzx.iteam;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.lzx.iteam.adapter.CalendarListAdapter;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.bean.ScheduleData;
import com.lzx.iteam.bean.ScheduleListData;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.ScheduleDB;
import com.lzx.iteam.widget.schedulecalendar.CalendarAdapter;
import com.lzx.iteam.widget.schedulecalendar.ScrollableLayout;
import com.lzx.iteam.widget.schedulecalendar.SpecialCalendar;
import com.lzx.iteam.widget.schedulecalendar.ViewHelper;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.CustomGridView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Megan on 16/3/14.
 */
public class ScheduleCalendarActivity extends Activity implements View.OnClickListener, GestureDetector.OnGestureListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private LinearLayout mBtnBack, mNullLayout, mHelp;
    private ImageView mIvManager;
    private ImageView mIvCreate;
    private ImageView mIvPrevious, mIvNext;
    private TextView mTvYear, mTvMonth1, mTvMonth2;
    private ScrollableLayout mScrollLayout;
    private CustomGridView mGridView;
    private TextView mTvDay, mTvUserName;
    private ListView mListView;
    private Dialog mScheduleDialog;
    private RelativeLayout mLayoutTitle;


    private CalendarAdapter calV = null;  // 日历adapter
    private CalendarListAdapter mAdapter; // 我的日程列表的adapter
    private GestureDetector gestureDetector = null; // 日历手势
    private ScheduleCalendarActivity mActivity;
    private AllDialogUtil mDialogUtil;
    private Dialog mProgressDialog;


    private int jumpMonth = 0;      //每次滑动，增加或减去一个月,默认为0（即显示当前月）
    private int jumpYear = 0;       //滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
    private int mYear;  // 跳转的年份
    private int mMonth; // 跳转的月份
    private int mDay;   // 跳转的日子
    private int year_c = 0;  // 当前的年份
    private int month_c = 0; // 当前的月份
    private int day_c = 0;   // 当前的日子
    private int mPosition = -1; // 删除日程时记录位置
    private float location;             // 最终决定的收缩比例值
    private float currentLoction = 1f;  // 记录当天的收缩比例值
    private float selectLoction = 1f;   // 记录选择那一天的收缩比例值
    private String currentDate = "";
    private String scheduleYear;    // 选择的年份
    private String scheduleMonth;   // 选择的月份
    private String scheduleDay;     // 选择的日子
    private String mDate;
    private String mUserId;
    private String mUserName;
    private String mCalendarId;
    private String mDone = "0";    // 日程完成标志  1:完成  0：未完成
    private boolean mIsMy;         // 是不是查看自己的日程
    private String mType;          // 1.日程接口   9. 事件接口

    private HashMap<String, Object> mMap = new HashMap<String, Object>();
    private List<ScheduleListData> mListData = new ArrayList<ScheduleListData>(); // 我的日程列表数据
    private List<Object> mCalendarData = new ArrayList<Object>();                 // 日历列表数据
    private ScheduleDB mScheduleDb;
    private CloudDBOperation mCloudDBOperation;

    private static final int GET_LIST = 10001;
    private static final int DELETE_CALENDAR = 10002;
    private static final int CALENDAR_DONE = 10003;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case GET_LIST:
                    if (msg.arg1 == 0) {

                        mMap = (HashMap<String, Object>) msg.obj;
                        mListData = (List<ScheduleListData>) mMap.get("schedule");
                        calV.bindData(mListData);

                        mCalendarData = (List<Object>) mMap.get("calendar");
                        if (mCalendarData.size() == 0) {
                            mNullLayout.setVisibility(View.VISIBLE);
                        } else {
                            mNullLayout.setVisibility(View.GONE);
                        }
                        mAdapter.bindData(mCalendarData, mYear == year_c && mMonth == month_c && mDay == day_c);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case DELETE_CALENDAR:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        if (mPosition != -1) {
                            mScheduleDb.deleteOneSchedule(mDate, mCalendarId);
                            mCalendarData.remove(mPosition);
                            if (mYear == year_c && mMonth == month_c && mDay == day_c) {
                                mAdapter.setShowLine();
                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case CALENDAR_DONE:
                    if (msg.arg1 == 0) {
                        mScheduleDb.updateScheduleDone(mDate, mDone, mCalendarId, mUserId);
                        mCalendarData = mScheduleDb.findScheduleByDate(mDate, mUserId);
                        mAdapter.bindData(mCalendarData, mYear == year_c && mMonth == month_c && mDay == day_c);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_calendar_layout);
        initView();
        initProperty();
    }

    @Override
    protected void onResume() {
        super.onResume();

        LocalLogin localLogin = LocalLogin.getInstance();
        if (!localLogin.isLogedin()) {
            localLogin.login(this);
            if (!localLogin.isLogedin()) {
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }

        mCalendarData = mScheduleDb.findScheduleByDate(mDate, mUserId);
        mAdapter.bindData(mCalendarData, mYear == year_c && mMonth == month_c && mDay == day_c);
        mListData = mCloudDBOperation.findCalendarData(mUserId, mYear + "", mMonth + "");
        calV.bindData(mListData);
        getCalendarData(mYear + "", mMonth + "", mDay + "");
    }

    private void initView() {
        mLayoutTitle = (RelativeLayout) findViewById(R.id.rl_schedule_calendar_title);
        mBtnBack = (LinearLayout) findViewById(R.id.schedule_btn_back);
        mHelp = (LinearLayout) findViewById(R.id.schedule_ll_help);
        mIvManager = (ImageView) findViewById(R.id.schedule_iv_manager);
        mIvCreate = (ImageView) findViewById(R.id.schedule_iv_create);
        mIvPrevious = (ImageView) findViewById(R.id.calendar_iv_previous);
        mIvNext = (ImageView) findViewById(R.id.calendar_iv_next);
        mTvYear = (TextView) findViewById(R.id.calendar_tv_year);
        mTvMonth1 = (TextView) findViewById(R.id.calendar_tv_month1);
        mTvMonth2 = (TextView) findViewById(R.id.calendar_tv_month2);
        mScrollLayout = (ScrollableLayout) findViewById(R.id.calendar_scrollablelayout);
        mGridView = (CustomGridView) findViewById(R.id.calentar_gridview);
        mTvDay = (TextView) findViewById(R.id.calentar_tv_day);
        mListView = (ListView) findViewById(R.id.calendar_lv_content);
        mNullLayout = (LinearLayout) findViewById(R.id.calendar_ll_null);
        mTvUserName = (TextView) findViewById(R.id.schedule_tv_name);

        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        mIvPrevious.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        mBtnBack.setOnClickListener(this);
        mHelp.setOnClickListener(this);
        mIvManager.setOnClickListener(this);
        mIvCreate.setOnClickListener(this);
        mDialogUtil = new AllDialogUtil(this);
        mTvDay.setOnClickListener(this);
        mNullLayout.setOnClickListener(this);

    }

    public void initProperty() {
        mActivity = this;
        mScheduleDb = new ScheduleDB(mActivity);
        mCloudDBOperation = new CloudDBOperation(this);
        Intent intent = getIntent();
        mUserId = intent.getStringExtra("userId");
        String mUid = PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID, "－1");
        if (StringUtil.isEmpty(mUserId) || mUserId.equals(mUid)) {
            mUserId = mUid;
            mIsMy = true;
        } else {
            mIvManager.setVisibility(View.GONE);
            mIsMy = false;
        }
        mUserName = intent.getStringExtra("userName");
        if (!StringUtil.isEmpty(mUserName) && !mIsMy) {
            mTvUserName.append("(" + mUserName + ")");
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        currentDate = sdf.format(date);  //当期日期
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);

        mYear = year_c;
        mMonth = month_c;
        mDay = day_c;
        mDate = year_c + "_" + month_c + "_" + day_c;

        // TODO 计算当天的位置和收缩比例
        SpecialCalendar calendar = new SpecialCalendar();
        boolean isLeapYear = calendar.isLeapYear(year_c);
        int days = calendar.getDaysOfMonth(isLeapYear, month_c);
        int dayOfWeek = calendar.getWeekdayOfMonth(year_c, month_c);
        int todayPosition = day_c;
        if (dayOfWeek != 7) {
            days = days + dayOfWeek;
            todayPosition += dayOfWeek - 1;
        } else {
            todayPosition -= 1;
        }
        /**
         * 如果 少于或者等于35天显示五行 多余35天显示六行
         * 五行: 收缩比例是：0.25，0.5，0.75，1
         * 六行: 收缩比例是：0.2，0.4，0.6，0.8，1
         */
        if (days <= 35) {
            Constants.scale = 0.25f;
            currentLoction = (4 - todayPosition / 7) * Constants.scale;
        } else {
            Constants.scale = 0.2f;
            currentLoction = (5 - todayPosition / 7) * Constants.scale;
        }
        location = currentLoction;
        mScrollLayout.setVisibleHeight(46f);
        mScrollLayout.setOnScrollListener(new ScrollableLayout.OnScrollListener() {
            @Override
            public void onScroll(int currentY, int maxY) {

                ViewHelper.setTranslationY(mGridView, currentY * location);
            }
        });
        mScrollLayout.getHelper().setCurrentContainer(mListView);

        gestureDetector = new GestureDetector(this);
        calV = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);
        mGridView.setAdapter(calV);
        addGridView();
        addTextToTopTextView();

        mAdapter = new CalendarListAdapter(this, mIsMy);
        mListView.setAdapter(mAdapter);


    }

    /**
     * 获取日历列表 和 日程列表
     *
     * @param year
     * @param month
     * @param day
     */
    public void getCalendarData(String year, String month, String day) {
        mDate = year + "_" + month + "_" + day;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_DATE, year + "_" + month));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_DAY, day + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_BOSS_UID, mUserId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        GetCalendarMsg msg = new GetCalendarMsg(mHandler.obtainMessage(GET_LIST), this, year, month, day, mUserId);
        msg.mParams = nvps;
        msg.mApi = AsynHttpClient.API_EVENT_CALENDAR_LIST;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    public void setDone(String eventId, String done) {
        mCalendarId = eventId;
        mDone = done;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_BOSS_UID, mUserId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, eventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_DONE, done));

        CalenderDoneMsg msg = new CalenderDoneMsg(mHandler.obtainMessage(CALENDAR_DONE));
        msg.mParams = nvps;
        msg.mApi = AsynHttpClient.API_EVENT_CALENDAR_DONE;
        AsynHttpClient.getInstance(this).execEventHttp(msg);
//        httpReqDlgShow();
    }

    /**
     * 删除日程
     *
     * @param calendarId api  1.日程删除   2.事件删除
     */
    private void deleteCalendar(String calendarId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, calendarId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(DELETE_CALENDAR));
        if ("1".equals(mType)) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CALENDAR_BOSS_UID, mUserId));
            msg.mApi = AsynHttpClient.API_EVENT_CALENDAR_DEL;
        } else {
            msg.mApi = AsynHttpClient.API_EVENT_REMOVE;
        }
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    private void httpReqDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).waitDialog();
//            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

    }

    private void httpReqDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.schedule_btn_back:
                finish();
                break;
            case R.id.schedule_iv_manager:
                showScheduleDialog();
                break;
            case R.id.schedule_iv_create:
                Intent create = new Intent(mActivity, ScheduleCreateActivity.class);
                create.putExtra("userId", mUserId);
                create.putExtra("isMe", mIsMy);
                create.setAction("createSchedule");
                startActivity(create);
                break;
            case R.id.calendar_iv_previous:
                changeView(false);
                break;
            case R.id.calendar_iv_next:
                changeView(true);
                break;
            case R.id.schedule_ll_help:
                Intent intent = new Intent(this, WebViewActivity.class);
                if (mIsMy) {
                    intent.putExtra("title", "如何设置日程表管理员?");
                    intent.putExtra("type", 1);
                } else {
                    intent.putExtra("title", "如何给员工安排日程?");
                    intent.putExtra("type", 10);
                }
                startActivity(intent);
                break;
            case R.id.calentar_tv_day:
            case R.id.calendar_ll_null:
                break;
        }
    }

    /**
     * 日程操作
     */
    private void showScheduleDialog() {

        mScheduleDialog = new AlertDialog.Builder(mActivity)
                .create();
        mScheduleDialog.show();
        Window window = mScheduleDialog.getWindow();
        WindowManager.LayoutParams lp = mScheduleDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha=0.5f; // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.schedule_dialog_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        LinearLayout manager = (LinearLayout) window.findViewById(R.id.ll_schendule_manager);
        manager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent manager = new Intent(mActivity, ScheduleManagerActivity.class);
                manager.setAction("schedule_manager");
                startActivity(manager);
                mScheduleDialog.dismiss();
            }
        });

        LinearLayout schedule = (LinearLayout) window.findViewById(R.id.ll_schendule_social);
        schedule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent member = new Intent(mActivity, ScheduleManagerActivity.class);
                member.setAction("schedule_member");
                startActivity(member);
                mScheduleDialog.dismiss();
            }
        });

        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScheduleDialog.dismiss();
            }
        });

    }


    private void changeView(boolean flag) {
        if (flag) {
            //像左滑动
            jumpMonth++;     //下一个月
            mMonth++;
            if (mMonth > 12) {
                mMonth = 1;
                mYear++;
            }
        } else {
            //向右滑动
            jumpMonth--;     //上一个月
            mMonth--;
            if (mMonth < 1) {
                mMonth = 12;
                mYear--;
            }
        }
        updateView();
    }

    //添加gridview
    private void addGridView() {

        if (jumpMonth == 0) {
            location = currentLoction;
        } else {
            location = 1f;
        }
        if (((jumpMonth + month_c) + "").equals(Constants.zMonth) && jumpMonth != 0) {
            location = selectLoction;
        }

        Log.d("location", "location == " + location + "   currentLoction == " + currentLoction);

        mGridView.setOnTouchListener(new View.OnTouchListener() {
            //将gridview中的触摸事件回传给gestureDetector
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return mActivity.gestureDetector.onTouchEvent(event);
            }
        });

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //gridView中的每一个item的点击事件
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                //点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
                int startPosition = calV.getStartPositon();
                int endPosition = calV.getEndPosition();

                if (Constants.scale == 0.2f) {
                    location = (5 - position / 7) * Constants.scale;
                } else {
                    location = (4 - position / 7) * Constants.scale;
                }
                selectLoction = location;
                if (startPosition <= position + 7 && position <= endPosition - 7) {
                    scheduleDay = calV.getDateByClickItem(position).split("\\.")[0];  //这一天的阳历
//                    String scheduleLunarDay = calV.getDateByClickItem(position).split("\\.")[1];  //这一天的阴历
                    scheduleYear = calV.getShowYear();
                    scheduleMonth = calV.getShowMonth();
                    Constants.zYear = scheduleYear;
                    Constants.zMonth = scheduleMonth;
                    Constants.zDay = scheduleDay;
                    calV.notifyDataSetChanged();
                    mYear = Integer.parseInt(scheduleYear);
                    mMonth = Integer.parseInt(scheduleMonth);
                    mDay = Integer.parseInt(scheduleDay);
                    setData();

                }
            }

        });
    }

    /**
     * 更新年月
     *
     * @param
     */
    public void addTextToTopTextView() {
        mTvYear.setText(calV.getShowYear() + "年");
        int month = Integer.parseInt(calV.getShowMonth());
        int month1 = month / 10;
        int month2 = month % 10;
        mTvMonth1.setText(month1 + "");
        mTvMonth2.setText(month2 + "");

    }

    /**
     * 显示选择的 日期
     *
     * @param year
     * @param month
     * @param day
     */
    private void setSelectDay(int year, int month, int day) {
        String time = month + "月" + day + "日";
        if (year == year_c && month == month_c) {
            int d = day - day_c;
            switch (d) {
                case -2:
                    time = "前天";
                    break;
                case -1:
                    time = "昨天";
                    break;
                case 0:
                    time = "今天";
                    break;
                case 1:
                    time = "明天";
                    break;
                case 2:
                    time = "后天";
                    break;
                default:
                    mTvDay.setText(month + "月" + day + "日");
                    break;
            }
            mTvDay.setText(time);
        } else {
            if (year == year_c) {
                mTvDay.setText(month + "月" + day + "日");
            } else {
                mTvDay.setText(year + "年" + month + "月" + day + "日");
            }
        }
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    /**
     * 滑动的手势监听
     *
     * @param e1
     * @param e2
     * @param velocityX
     * @param velocityY
     * @return
     */
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e1.getX() - e2.getX() > 120) {
            //像左滑动
            jumpMonth++;     //下一个月
            mMonth++;
            if (mMonth > 12) {
                mMonth = 1;
                mYear++;
            }
            updateView();
            return true;
        } else if (e1.getX() - e2.getX() < -120) {
            //向右滑动
            jumpMonth--;     //上一个月
            mMonth--;
            if (mMonth < 1) {
                mMonth = 12;
                mYear--;
            }
            updateView();
            return true;
        }
        return false;
    }

    /**
     * 月份切换，刷新日历表
     */
    private void updateView() {
        addGridView();   //添加一个gridView
        calV = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c);
        mGridView.setAdapter(calV);
        addTextToTopTextView();
        Log.d("Year and Month", "changeView  Month == " + mMonth + "   Year  == " + mYear);
        if (jumpMonth == 0) {
            Constants.zYear = "";
            Constants.zMonth = "";
            Constants.zDay = "";
            mDay = day_c;
        } else {
            if (Constants.zYear.equals(mYear + "") && Constants.zMonth.equals(mMonth + "")) {
                mDay = Integer.parseInt(Constants.zDay);
            } else {
                mDay = 1;
            }
        }
        setData();

    }

    private void setData() {
        mDate = mYear + "_" + mMonth + "_" + mDay;
        mCalendarData = mScheduleDb.findScheduleByDate(mDate, mUserId);
        if (mCalendarData.size() > 0) {
            mNullLayout.setVisibility(View.GONE);
        } else {
            mNullLayout.setVisibility(View.VISIBLE);
        }
        mAdapter.bindData(mCalendarData, mYear == year_c && mMonth == month_c && mDay == day_c);
        mListData = mCloudDBOperation.findCalendarData(mUserId, mYear + "", mMonth + "");
        calV.bindData(mListData);
        getCalendarData(mYear + "", mMonth + "", mDay + "");
        setSelectDay(mYear, mMonth, mDay);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (mCalendarData.get(position) instanceof ScheduleData) {
            ScheduleData scheduleData = (ScheduleData) mCalendarData.get(position);
            if (!mIsMy && "1".equals(scheduleData.getHidden())) {
                Toast.makeText(mActivity, "您没有权限查看此日程", Toast.LENGTH_SHORT).show();
                return;
            } else {
                Intent schedule = new Intent(this, ScheduleDetailActivity.class);
                schedule.putExtra("scheduleData", (ScheduleData) mCalendarData.get(position));
                schedule.putExtra("userId", mUserId);
                schedule.putExtra("isMe", mIsMy);
                startActivity(schedule);
            }
        } else {
            Intent event = new Intent(this, EventDetailContentActivity.class);
            event.putExtra("event_msg", (EventListData) mCalendarData.get(position));
            startActivity(event);
        }


    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

        if (mCalendarData.get(position) instanceof ScheduleData) {
            ScheduleData data = (ScheduleData) mCalendarData.get(position);
            mCalendarId = data.getId();
            mType = "1";
        } else {
            EventListData eventListData = (EventListData) mCalendarData.get(position);
            mCalendarId = eventListData.getEventId();
            mType = "9";
        }
        if ("1".equals(mType) && !mIsMy && "1".equals(((ScheduleData) mCalendarData.get(position)).getHidden())) {
            Toast.makeText(mActivity, "您没有权限删除此日程", Toast.LENGTH_SHORT).show();
        } else {
            mPosition = position;
            String okText = this.getString(R.string.label_btn_delete);
            String cancelText = this.getString(R.string.cancel);
            mDialogUtil.titleDeleteMsgStyle(okText, cancelText, "删除此日程");
            mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                @Override
                public void onConfirmClick(Dialog lDialog) {
                    httpReqDlgShow();
                    deleteCalendar(mCalendarId);
                    lDialog.dismiss();
                }

                @Override
                public void onCancelClick(Dialog lDialog) {
                    lDialog.dismiss();
                }
            });
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // TODO 页面被销毁时，清空选择的日期数据
        Constants.zYear = "";
        Constants.zMonth = "";
        Constants.zDay = "";
    }


}
